﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Sustainalytics.Claims;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.ESGRatings.BusinessLogic.ESGOnlineReport;
using Sustainalytics.ESGRatings.Service.Models;
using Sustainalytics.Utils;
using Sustainalytics.Auth.Claims;
using Sustainalytics.ESG.Entities;
using Sustainalytics.Utils.WebApi.ErrorCodes;
using System.Web.Http.Cors;

namespace Sustainalytics.ESGRatings.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [ClaimsChecker("api/v1/company/esg")]
    [RoutePrefix("api/v1/company")]
    //[AutoInvalidateCacheOutput]
    [LogControllerFilter(true, true, false)]
    public class EsgControversyIndicatorController : ApiController
    {
        [Route("{companyId}/esgControversyIndicator")]
       // [CacheOutput(ServerTimeSpan = 100, ClientTimeSpan = 0, NoCache = true, MustRevalidate = true, Private = true)]
        [UniverseChecker("universeIds")]
        public HttpResponseMessage Get(Guid companyId,[FromUri]Guid EsgProfileId, [FromUri]AccountFeature feature, [FromUri]int[] universeIds = null)
        {
            try
            {

                var data = _service.GetControversyIndicatorsByCompanyId(companyId, universeIds);


                // ReSharper disable once InconsistentNaming
                var DTOs = (from indicator in data.Where(x=>x.AnswerCategory>0).ToList()
                    group indicator by new {indicator.AnswerCategory,indicator.Template.Name}
                    into g
                    select new EsgControversyIndicatorDto
                    {
                        AnswerCategory = g.Key.AnswerCategory,
                        Events = g.SelectMany(x => x.EventIndicators.Where(ev => ev.AnswerCategory > 0).Select(ev=>new EsgEventDto(ev.ControversyIndicatorName,ev.Name))).ToArray()
                    }).ToList();





                return Request.CreateResponse(HttpStatusCode.OK, DTOs);


            }
            catch (ESGReasearchNotFoundException)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = "ESGReasearchNotFoundException",
                    message = "Research not available."
                });
                   
            }
            catch (ESGReasearchNotInUniversesException)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = "ESGReasearchNotInUniversesException",
                    message = "Research available with additional subscription."
                });
                
            }
            catch (Exception ex)
            {
                CommonEventSource.Log.Exception(ex);
                return Request.CreateResponse(HttpStatusCode.InternalServerError,
                    new { ErrorStatusCode = WebAPIGeneralErrorCodes.UnhandledException });
            }
        }


        private IOnlineResearchProductsBusinessLogicUnit _service;


        public EsgControversyIndicatorController()
        {
            Setup();
        }

        public EsgControversyIndicatorController(
            IOnlineResearchProductsBusinessLogicUnit service)
        {
            _service = service;
        }


        private void Setup()
        {
            IRepositoryCollection<RPControversyIndicator> repo = new RepositoryCollection<RPControversyIndicator>(ClientDWConnection.GetConnectionString());
            _service = _service ?? new OnlineResearchProductsBusinessLogicUnit(repo);
        }
    }

}
